package com.warmlight.voicepacket.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.warmlight.voicepacket.R;
import com.warmlight.voicepacket.adapter.TopicPagerAdapter;
import com.warmlight.voicepacket.base.BaseFragment;
import com.warmlight.voicepacket.data.PlaydeatalData;
import com.warmlight.voicepacket.data.RecommendData;
import com.warmlight.voicepacket.data.eventbus.AudioCompleted;
import com.warmlight.voicepacket.data.eventbus.CollectSingleAudio;
import com.warmlight.voicepacket.data.eventbus.ShareUnlock;
import com.warmlight.voicepacket.http.HttpClient;
import com.warmlight.voicepacket.http.HttpConfig;
import com.warmlight.voicepacket.http.HttpUtils;
import com.warmlight.voicepacket.http.ResponseData;
import com.warmlight.voicepacket.ui.search.SearchActivity;
import com.warmlight.voicepacket.utils.ClickLog;
import com.warmlight.voicepacket.widget.CoverLoading;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.TreeMap;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;

import static com.warmlight.voicepacket.data.TempData.mLastAnime;
import static com.warmlight.voicepacket.data.TempData.mLastData;
import static com.warmlight.voicepacket.data.TempData.mLastView;

public class RecommendFragment extends BaseFragment implements View.OnClickListener {

    private CoverLoading cover;
    private TabLayout tl_topic;
    private ViewPager vp_topic;
    private TopicPagerAdapter mTopicAdapter;
    private static final int FILL_TOPIC = 0;
    private static final int FILL_RECOMMEND = 1;
    private static final int FILL_FEED = 2;
    //主页话题标题tab
    private List<RecommendData.DataBean.CategoryBean> tabList = new ArrayList<>();
    //主页推荐播单list
//    private List<RecommendData.DataBean.PlayCoversBean> recommendList = new ArrayList<>();
    //主页feedlist
//    private List<RecommendData.DataBean.AudioListBean> feedList = new ArrayList<>();
    private LinearLayout ll_search;
    private TextView tv_search_key;
    private RecommendData.DataBean.ShareBean share;
    private ImageView iv_share_app;


    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mView = inflater.inflate(R.layout.fragment_recommend, container, false);

        initViews();
        EventBus.getDefault().register(this);
        getAllData();

        return mView;
    }

    /**
     * 分享解锁回调
     * @param messageEvent
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void XXX(ShareUnlock messageEvent) {
        if (mTopicAdapter != null){
            mTopicAdapter.updata(vp_topic.getCurrentItem(),messageEvent.islist,messageEvent.item,messageEvent.getCover_id());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void xxxx(CollectSingleAudio collectSingleAudio){
        if (mTopicAdapter != null){
            mTopicAdapter.notifyCollect(collectSingleAudio.getAudioId());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //(sticky = true)
    public void onEvent(AudioCompleted data){
        if(mLastData != null && mLastView != null && mLastAnime != null){
            mLastView.setImageResource(R.drawable.icon_audio_play);
            mLastData.setPlaying(false);
            Drawable d = mLastAnime.getDrawable();
            if(d instanceof AnimationDrawable){
                ((AnimationDrawable)mLastAnime.getDrawable()).stop();
                mLastAnime.setImageResource(R.drawable.frame3);
            }
        }
    }

    @SuppressLint("CheckResult")
    private void getAllData(){
        HttpClient.getInstance().postRxAndroidAES(HttpConfig.SERVER+HttpConfig.DISCOVER,new TreeMap<String, String>())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<ResponseData>() {
                    @Override
                    public void accept(ResponseData responseData) throws Exception {
                        if (HttpUtils.isCodeSuccess(responseData.getCode())){
                            final RecommendData data = new Gson().fromJson(responseData.getBody(),RecommendData.class);

                            if(data.getData() == null){
//                                getActivity().runOnUiThread(new Runnable() {
//                                    @Override
//                                    public void run() {
                                        if(cover!=null){
                                            cover.setResult(CoverLoading.LoadingResult.NULL);
                                        }
//                                    }
//                                });
                                return;
                            }

                            tabList = data.getData().getCategory();
//                recommendList = data.getData().getPlay_covers();
//                feedList = data.getData().getAudio_list();

//                            mHandler.sendEmptyMessage(FILL_TOPIC);取消mhandler
                            fillTopic(tl_topic,tabList);
                            //main thread touch its view
//                    mTopicAdapter.setList(tabList);
                            mTopicAdapter = new TopicPagerAdapter(getContext(), tabList);
                            vp_topic.setAdapter(mTopicAdapter);
                            if(cover!=null){
                                cover.setResult(CoverLoading.LoadingResult.SUCCESS);
                            }

//                            mHandler.sendEmptyMessage(FILL_RECOMMEND);取消mhandler
                            fillRecommend();

//                            mHandler.post(new Runnable() {
//                                @Override
//                                public void run() {
                                    tv_search_key.setText(data.getData().getSearch_key());
//                                }
//                            });

                            share = data.getData().getShare();
                        }else{
                            if(cover!=null){
                                cover.setResult(CoverLoading.LoadingResult.NULL);
                            }
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if(cover!=null){
                            cover.setResult(CoverLoading.LoadingResult.FAIL);
                        }
                    }
                });
//        HttpClient.post(HttpConfig.SERVER+HttpConfig.DISCOVER, new TreeMap<String, String>(), new Callback() {
//            @Override
//            public void onFailure(Call call, IOException e) {
//                if (getActivity() != null){
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if(cover!=null){
//                                cover.setResult(CoverLoading.LoadingResult.FAIL);
//                            }
//                        }
//                    });
//                }
//            }
//
//            @Override
//            public void onResponse(Call call, String response) {
////                String s = response.body().string();
//                final RecommendData data = new Gson().fromJson(response,RecommendData.class);
//
//                if(data.getData() == null){
//                    getActivity().runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if(cover!=null){
//                                cover.setResult(CoverLoading.LoadingResult.NULL);
//                            }
//                        }
//                    });
//                    return;
//                }
//
//                tabList = data.getData().getCategory();
////                recommendList = data.getData().getPlay_covers();
////                feedList = data.getData().getAudio_list();
//
//                mHandler.sendEmptyMessage(FILL_TOPIC);
//
//                mHandler.sendEmptyMessage(FILL_RECOMMEND);
//
//                mHandler.post(new Runnable() {
//                    @Override
//                    public void run() {
//                        tv_search_key.setText(data.getData().getSearch_key());
//                    }
//                });
//
//                share = data.getData().getShare();
//
//            }
//        });
    }

    private void initViews() {

        cover = (CoverLoading) findViewById(R.id.cover);
        cover.setVisibility(View.VISIBLE);
        cover.setOnReloadClickListener(new CoverLoading.ReloadListener() {
            @Override
            public void onReloadClicked() {
                getAllData();
            }
        });
        cover.setResult(CoverLoading.LoadingResult.LOADING);

        tl_topic = (TabLayout) findViewById(R.id.tl_topic);
        vp_topic = (ViewPager) findViewById(R.id.vp_topic);
        //搜索框中的提示文字
        tv_search_key = (TextView) findViewById(R.id.tv_search_key);
        //分享
        iv_share_app = (ImageView) findViewById(R.id.iv_share_app);
        iv_share_app.setOnClickListener(this);

        ll_search = (LinearLayout) findViewById(R.id.ll_search);
        ll_search.setOnClickListener(this);
//        mTopicAdapter = new TopicPagerAdapter(getContext(), tabList);
//        vp_topic.setAdapter(mTopicAdapter);
//        tl_topic.getTabAt(1).select();
        tl_topic.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                vp_topic.setCurrentItem(tab.getPosition());
                //TODO 申请相关页面数据

            }
            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }
            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        vp_topic.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
            }
            @Override
            public void onPageSelected(int position) {
                if(tl_topic.getSelectedTabPosition() != position){
                    tl_topic.getTabAt(position).select();
                }
                String id = tabList.get(position).getId();
                ClickLog.clickLog(ClickLog.dis_tab,"0",id);
            }
            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
//        tl_topic.post(new Runnable() {
//            @Override
//            public void run() {
//                setIndicator(tl_topic,0,0);
//            }
//        });
    }

//    private Handler mHandler = new Handler(new Handler.Callback() {
//        @Override
//        public boolean handleMessage(Message msg) {
//            switch (msg.what){
//                case FILL_TOPIC:
//                    fillTopic(tl_topic,tabList);
//                    //main thread touch its view
////                    mTopicAdapter.setList(tabList);
//                    mTopicAdapter = new TopicPagerAdapter(getContext(), tabList);
//                    vp_topic.setAdapter(mTopicAdapter);
//                    if(cover!=null){
//                        cover.setResult(CoverLoading.LoadingResult.SUCCESS);
//                    }
//                    break;
//                case FILL_RECOMMEND:
//                    fillRecommend();
//                    break;
//                default:
//                    break;
//            }
//            return false;
//        }
//    });

    private void fillRecommend(){
//        mTopicAdapter.setRecommendData(recommendList,feedList);
    }

    //填充topic数据
    private void fillTopic(TabLayout tl, List<RecommendData.DataBean.CategoryBean> list) {
        if(tl!=null){
            tl.removeAllTabs();
        }
        for (RecommendData.DataBean.CategoryBean temp : list) {
            tl.addTab(tl.newTab().setText(temp.getName()));
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.ll_search:
                String key = tv_search_key.getText().toString();
                Intent intent = new Intent(getContext(),SearchActivity.class);
                intent.putExtra("searchKey",key);
                startActivity(intent);
                break;
            case R.id.iv_share_app:
                if (share != null){
                    //如果有锁就去跳转分享
                    PlaydeatalData.DataBean.ShareBean shareBean = new PlaydeatalData.DataBean.ShareBean();
                    shareBean.setDesc(share.getDesc());
                    shareBean.setH5_url(share.getH5_url());
                    shareBean.setPic_url(share.getPic_url());
                    shareBean.setTitle(share.getTitle());
                    new CustomBottomSheetDialogFragment(shareBean).show(getActivity().getSupportFragmentManager(), "shareapp");
                }
                break;
        }
    }


    //设置指示器长度的方法
//    public void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
//        Class<?> tabLayout = tabs.getClass();
//        Field tabStrip = null;
//        try {
//            tabStrip = tabLayout.getDeclaredField("mTabStrip");
//        } catch (NoSuchFieldException e) {
//            e.printStackTrace();
//        }
//
//        tabStrip.setAccessible(true);
//        LinearLayout llTab = null;
//        try {
//            llTab = (LinearLayout) tabStrip.get(tabs);
//        } catch (IllegalAccessException e) {
//            e.printStackTrace();
//        }
//
//        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
//        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
//
//        for (int i = 0; i < llTab.getChildCount(); i++) {
//            View child = llTab.getChildAt(i);
//            child.setPadding(0, 0, 0, 0);
////            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
//            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
//            params.leftMargin = left;
//            params.rightMargin = right;
//            child.setLayoutParams(params);
//            child.invalidate();
//        }
//    }
}
